package com.xiantm.study.thread.readwritelock;

import java.util.Random;

public class WriterThread extends Thread{
    private final Data data;
    private final String text;
    private int index = 0;
    private final Random random = new Random();

    public WriterThread(Data data, String text){
        this.data = data;
        this.text = text;
    }

    @Override
    public void run(){
        try {
            while (true){
                char c = nextChar();
                data.write(c);
                sleep(random.nextInt(3000));
            }
        } catch (InterruptedException e){

        }

    }

    private char nextChar(){
        char c = text.charAt(index++);
        if (index >= text.length()){
            index = 0;
        }
        return c;
    }
}